package com.ruoyi.enterprise.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.enterprise.domain.ComHot;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.enterprise.domain.ComTxHistory;
import com.ruoyi.enterprise.service.IComTxHistoryService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 本金计算Controller
 *
 * @author ruoyi
 * @date 2024-03-07
 */
@RestController
@RequestMapping("/enterprise/cost")
public class ComTxHistoryController extends BaseController {
    @Autowired
    private IComTxHistoryService comTxHistoryService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private HttpServletRequest request;

    /**
     * 查询本金计算列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:cost:list')")
    @GetMapping("/list")
    public TableDataInfo list(ComTxHistory comTxHistory) {
        setUserId(comTxHistory);
        startPage();
        List<ComTxHistory> list = comTxHistoryService.selectComTxHistoryList(comTxHistory);
        return getDataTable(list);
    }

    /**
     * 导出本金计算列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:cost:export')")
    @Log(title = "本金计算", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ComTxHistory comTxHistory) {
        setUserId(comTxHistory);
        List<ComTxHistory> list = comTxHistoryService.selectComTxHistoryList(comTxHistory);
        ExcelUtil<ComTxHistory> util = new ExcelUtil<ComTxHistory>(ComTxHistory.class);
        util.exportExcel(response, list, "本金计算数据");
    }

    /**
     * 获取本金计算详细信息
     */
    @PreAuthorize("@ss.hasPermi('enterprise:cost:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(comTxHistoryService.selectComTxHistoryById(id));
    }

    /**
     * 新增本金计算
     */
    @PreAuthorize("@ss.hasPermi('enterprise:cost:add')")
    @Log(title = "本金计算", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ComTxHistory comTxHistory) {
        setUserId(comTxHistory);
        return toAjax(comTxHistoryService.insertComTxHistory(handleData(comTxHistory)));
    }

    /**
     * 修改本金计算
     */
    @PreAuthorize("@ss.hasPermi('enterprise:cost:edit')")
    @Log(title = "本金计算", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ComTxHistory comTxHistory) {
        setUserId(comTxHistory);
        return toAjax(comTxHistoryService.updateComTxHistory(handleData(comTxHistory)));
    }

    /**
     * 删除本金计算
     */
    @PreAuthorize("@ss.hasPermi('enterprise:cost:remove')")
    @Log(title = "本金计算", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(comTxHistoryService.deleteComTxHistoryByIds(ids));
    }

    public ComTxHistory handleData(ComTxHistory comTxHistory) {
        // 成本股价
        BigDecimal originPrice = comTxHistory.getStockPriceCost();
        // 历史持股
        BigDecimal originCount = comTxHistory.getStockCount();
        //当前股价
        BigDecimal nowPrice = comTxHistory.getStockPriceCurrent();
        // 增加数量
        BigDecimal changeCount = comTxHistory.getStockCountChangeAmount();
        BigDecimal buyCount = changeCount;
        BigDecimal sellCount = changeCount.compareTo(originCount) > 0 ? originCount : changeCount;
        // 加仓后新的成本
        BigDecimal newPricePlus = originPrice.multiply(originCount)
                .add(nowPrice.multiply(buyCount))
                .divide(originCount.add(buyCount), 3, RoundingMode.HALF_UP);
        // 增金额
        comTxHistory.setStockBuyAmount(nowPrice.multiply(buyCount));
        comTxHistory.setStockPriceCostAfterBuy(newPricePlus);
        comTxHistory.setStockCountAfterBuy(buyCount.add(originCount));
        // 减持后的成本
        BigDecimal newPriceMinus = new BigDecimal(0);
        if (originCount.compareTo(sellCount) != 0) {
            newPriceMinus = originPrice.multiply(originCount)
                    .subtract(nowPrice.multiply(sellCount))
                    .divide(originCount.subtract(sellCount), 3, RoundingMode.HALF_UP);
        }
//减持金额
        comTxHistory.setStockSellAmount(nowPrice.multiply(sellCount));
        comTxHistory.setStockPriceCostAfterSell(newPriceMinus);
        BigDecimal countAfterSell = originCount.subtract(sellCount);
        System.out.println("countAfterSell " + countAfterSell);
        comTxHistory.setStockCountAfterSell(countAfterSell);
//        计算盈亏
        BigDecimal diffCost = nowPrice.subtract(originPrice);
        BigDecimal yk = diffCost.multiply(originCount);
        comTxHistory.setGainAndLoss(yk);
        return comTxHistory;
    }
    /**
     * 非管理员用户,只能获取自己的热门股票信息
     * @param comHot
     */
    public void setUserId(ComTxHistory comHot) {
        // 获取角色名
        LoginUser loginUser = tokenService.getLoginUser(request);
        List<SysRole> roleName = loginUser.getUser().getRoles();
        for (SysRole sysRole : roleName) {
            if (sysRole.isAdmin()) {
//                comHot.setUserId(null);
                return;
            } else {
                comHot.setUserId(loginUser.getUserId());
            }
        }
    }

}
